<template>
  <a-card>
    <template v-for="schema in getSchemas" :key="schema">
      <OneForOneItem
        v-if="showComponent(schema)"
        :refreshFieldObj="refreshFieldObj"
        :form-api="formApi"
        :schema="schema"
        :mainKey="mainKey"
        :isWorkFlow="isWorkFlow"
        v-model:value="data[0][schema.field]"
      />
      <!-- <FormItem
        v-if="getShow(schema)"
        :name="[mainKey, 0, schema.field]"
        :key="schema.key"
        :label="schema.label"
        :label-col="getLabelCol(schema.componentProps)"
        :rules="getRules(schema)"
        :validateTrigger="['blur', 'change']"
      >
        <component
          v-if="getShow(schema)"
          :is="componentMap.get(schema.component)"
          :disabled="props.disabled"
          :size="formProps?.size"
          v-bind="getComponentsProps(schema)"
          v-model:value="data![0][schema.field]"
        />
      </FormItem> -->
    </template>
  </a-card>
</template>
<script lang="ts" setup>
  import { computed, ref, unref, watch } from 'vue';
  import { FormActionType, FormSchema } from '../../Form';
  import OneForOneItem from './components/OneForOneItem.vue';
  import { noShowGenerateComponents, noShowWorkFlowComponents } from '../../Form/src/helper';

  const emit = defineEmits(['change', 'update:value']);

  const props = defineProps({
    /**
     * 如果是编辑状态 默认现实的值
     */
    value: { type: Array as PropType<Recordable[]>, default: () => [] },
    /**
     * 需要绑定主表的字段  用于验证  必填
     */
    mainKey: { type: String, required: true },
    /**
     * 子表单配置
     */
    childSchemas: {
      type: Array as PropType<FormSchema[]>,
      required: true,
    },
    /**
     * 是否禁用所有组件
     */
    disabled: {
      type: Boolean,
      default: false,
    },
    formApi: {
      type: Object as PropType<FormActionType>,
    },
    //是否是工作流
    isWorkFlow: {
      type: Boolean,
      default: false,
    },
    //刷新api使用
    refreshFieldObj: {
      type: Object,
      default: () => {},
    },
  });

  const data = ref<Recordable>([{}]);
  // emit('change', unref(data));
  // emit('update:value', unref(data));

  // 记得引用FormApi  并且将formApi.formState.values 传递到子表单中
  const getSchemas = computed(() => {
    return props.childSchemas;
  });

  watch(
    () => props.value,
    () => {
      if (!props.value || props.value.length === 0) {
        data.value = [{}];
      } else {
        data.value = props.value;
      }
      //要保证在预加载之后在emit  不然预加载数据不会绑定到表单数据中
      emit('change', unref(data));
      emit('update:value', unref(data));
    },
    { deep: true },
  );

  function showComponent(schema) {
    return props.isWorkFlow
      ? !noShowWorkFlowComponents.includes(schema.type)
      : !noShowGenerateComponents.includes(schema.type);
  }
</script>
